﻿using Microsoft.AspNetCore.Antiforgery;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Quartz.MUI.ClassLibrary.Extensions
{
    public static class HttpClientFactoryExtension
    {
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        public static async Task<string> HttpSendAsync(this IHttpClientFactory httpClientFactory, HttpMethod method, string url,string parmet, Dictionary<string, string> headers = null)
        {
            var client = httpClientFactory.CreateClient();
            if (url.StartsWith("https", System.StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 |
                                                       SecurityProtocolType
                                                           .Tls12; //必须加上这一句，根据需要更改值
                var handler = new HttpClientHandler();
                handler.ServerCertificateCustomValidationCallback = CheckValidationResult;
                client = new HttpClient(handler);
                client.DefaultRequestVersion = HttpVersion.Version11;
            }
            var postContent = new StringContent(parmet, Encoding.UTF8, "application/json");
           // var content = new StringContent("");
            // content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            var request = new HttpRequestMessage(method, url)
            {
                Content = postContent
            };
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }
            try
            {
                HttpResponseMessage httpResponseMessage = await client.SendAsync(request);

                var result = await httpResponseMessage.Content
                    .ReadAsStringAsync();
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
